package com.atguigu.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.atguigu.spzx.manager.service.ValidateCodeService;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author wx
 * @version 1.0
 * @description: TODO
 * @date 2024/11/6 15:38
 */
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 获取验证码
     *
     * @return
     */
    @Override
    public ValidateCodeVo generateValidateCode() {
        //生成验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 10);
        //获取验证码的内容
        String code = circleCaptcha.getCode();
        //获取验证码图案
        String imageBase64 = circleCaptcha.getImageBase64();
        //生成存储redis的key
        String validateKey = UUID.randomUUID().toString().replaceAll("-", "");
        //存储redis
        redisTemplate.opsForValue().set("user:login:validatecode:" + validateKey, code, 5, TimeUnit.MINUTES);
        //封装返回值对象
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeValue("data:image/png;base64,"+imageBase64);
        validateCodeVo.setCodeKey(validateKey);
        return validateCodeVo;
    }
}
